package com.wf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wf.domain.Menu;
import com.wf.mapper.MenuMapper;
import com.wf.service.MenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author mpk16
* @description 针对表【menu】的数据库操作Service实现
* @createDate 2024-08-03 13:39:49
*/
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu>
    implements MenuService{
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> selectMenu(String menu_name, Integer parent_id) {
        return menuMapper.selectMenu(menu_name,parent_id);
    }
    @Override
    public List<Menu> selectTreeMenu(){
        //一次把所有的数据都查出来
        List<Menu> regions = menuMapper.selectList(null);
        List<Menu> allList = regions.stream().map(p -> {
            Menu vo = new Menu();
            BeanUtils.copyProperties(p, vo);
            return vo;
        }).collect(Collectors.toList());
        //指定根节点的parentId
        return buildChildren(0, allList);
    }

    private List<Menu> buildChildren(Integer parentId, List<Menu> allList){
        List<Menu> voList = new ArrayList<>();
        for (Menu item : allList) {
            //如果相等
            if (Objects.equals(item.getParentId(), parentId)) {
                //递归，自己调自己
                item.setChildrenList(buildChildren(item.getMenuId(), allList));
                voList.add(item);
            }
        }
        return voList;
    }
}




